import userAPI from '@/services/user';
import { PageContainer } from '@ant-design/pro-components';
import { useNavigate, useParams } from '@umijs/max';
import { message } from 'antd';
import { useEffect, useState } from 'react';
import UserForm from './components/userForm';

const EditUser = () => {
  const { id } = useParams();

  const [userInfo, setUserInfo] = useState(null);
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();

  const setNewUserInfo = (newInfo) => {
    setUserInfo(newInfo);
  };
  const submitHandle = async () => {
    const resp = await userAPI.editUser(userInfo._id, userInfo);
    console.log(resp, 'resp');
    if (resp.data) {
      messageApi.open({
        type: 'success',
        content: '修改用户信息成功！',
      });
      setTimeout(() => {
        navigate('/user/userList');
      }, 2000);
    } else {
      messageApi.open({
        type: 'error',
        content: resp.msg,
      });
    }
  };

  useEffect(() => {
    async function fetchData(id) {
      const { data } = await userAPI.getUserById(id);
      setUserInfo(data);
    }
    if (id) {
      fetchData(id);
    }
  }, [id]);

  return (
    <div>
      <PageContainer>
        <div className="container" style={{ width: '800px' }}>
          {userInfo ? (
            <UserForm
              type="edit"
              userInfo={userInfo}
              setUserInfo={setNewUserInfo}
              submitHandle={submitHandle}
            />
          ) : null}
        </div>
      </PageContainer>
      {contextHolder}
    </div>
  );
};

export default EditUser;
